package cn.eeepay.framework.dao.risk;

import cn.eeepay.framework.db.pagination.Page;
import cn.eeepay.framework.model.risk.TransLimitRule;
import cn.eeepay.framework.model.risk.TransLimitWhite;
import cn.eeepay.framework.util.StringUtil;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;
import java.util.Map;

public interface TransLimitDao {

    @SelectProvider(type=SqlProvider.class,method="selectTransLimitRuleList")
    @ResultType(TransLimitRule.class)
    List<TransLimitRule> selectTransLimitRuleList(@Param("info") TransLimitRule info, @Param("page") Page<TransLimitRule> page);

    @SelectProvider(type=SqlProvider.class,method="selectTransLimitRuleList")
    @ResultType(TransLimitRule.class)
    List<TransLimitRule> importTransLimitRuleList(@Param("info") TransLimitRule info);

    @Select("select * from trans_limit_rule where id = #{id} ")
    TransLimitRule selectTransLimitRuleDetail(@Param("id") Long id);

    @SelectProvider(type=SqlProvider.class,method="selectMinServiceManageQuota")
    @ResultType(Map.class)
    Map selectMinServiceManageQuota(@Param("teamId") String teamId, @Param("cardType") String cardType);

    @Select("select count(1) from trans_limit_rule where `status`!=-1 " +
            "and (rules_city like concat('%',#{city},'%') ) and card_type = #{cardType} " +
            "and (team_id like concat('%',#{teamId},'%') ) and limit_action = #{limitAction}")
    int selectTransLimitRuleCityCount(@Param("city") String city, @Param("cardType") String cardType,@Param("teamId") String teamId,@Param("limitAction") String limitAction);

    @Select("select count(1) from trans_limit_rule where `status`!=-1 " +
            "and (rules_city like concat('%',#{city},'%') ) and card_type = #{cardType} " +
            "and (team_id like concat('%',#{teamId},'%') ) and limit_action = #{limitAction} " +
            "and id != #{id} ")
    int selectTransLimitRuleCityCountById(@Param("city") String city, @Param("cardType") String cardType,@Param("teamId") String teamId,@Param("limitAction") String limitAction, @Param("id") Long id);

    @Insert("INSERT INTO trans_limit_rule ( limit_action, team_id, card_type, single_day_amount, single_count_amount," +
            " single_daycard_amount, single_daycard_count, rules_provinces, rules_city, create_person) VALUES " +
            "(#{info.limitAction},#{info.teamId},#{info.cardType},#{info.singleDayAmount},#{info.singleCountAmount}," +
            "#{info.singleDaycardAmount},#{info.singleDaycardCount},#{info.rulesProvinces},#{info.rulesCity},#{info.createPerson})")
    @SelectKey(statement = "select LAST_INSERT_ID()", keyProperty = "info.id", before = false, resultType = Long.class)
    int insertTransLimitRule(@Param("info") TransLimitRule info);

    @Update("UPDATE trans_limit_rule SET team_id=#{info.teamId}, card_type=#{info.cardType}," +
            " single_day_amount=#{info.singleDayAmount}, single_count_amount=#{info.singleCountAmount}," +
            " single_daycard_amount=#{info.singleDaycardAmount}, single_daycard_count=#{info.singleDaycardCount}," +
            " rules_provinces=#{info.rulesProvinces}, rules_city=#{info.rulesCity} WHERE id=#{info.id}")
    int updateTransLimitRule(@Param("info") TransLimitRule info);

    @Update("UPDATE trans_limit_rule SET `status`=#{status} WHERE id=#{id}")
    int updateTransLimitRuleStatus(@Param("status")Integer status,@Param("id")Long id);

    @Delete("UPDATE trans_limit_rule SET `status`=-1  where id=#{id}")
    int deleteTransLimitRule(@Param("id")Long id);


    @Insert("INSERT INTO trans_limit_rule_log ( limit_rule, `type`, create_person) VALUES " +
            "(#{limitRule},#{type},#{createPerson}) ")
    int insertTransLimitRuleLog(@Param("limitRule") Long limitRule ,@Param("type") String type ,@Param("createPerson") String createPerson );

    @Select("select * from trans_limit_rule_log where limit_rule=#{limitRule} ORDER BY create_time desc")
    @ResultType(Map.class)
    List<Map> selectTransLimitRuleLog(@Param("limitRule")Long limitRule);


    @SelectProvider(type=SqlProvider.class,method="selectTransLimitWhiteList")
    @ResultType(TransLimitWhite.class)
    List<TransLimitWhite> selectTransLimitWhiteList(@Param("info") TransLimitWhite info, @Param("page") Page<TransLimitWhite> page);

    @SelectProvider(type=SqlProvider.class,method="selectTransLimitWhiteList")
    @ResultType(TransLimitWhite.class)
    List<TransLimitWhite> importTransLimitWhiteList(@Param("info") TransLimitWhite info);

    @Select("select * from trans_limit_white_list where id = #{id} ")
    TransLimitWhite selectTransLimitWhiteDetail(@Param("id") Long id);

    @Select("select count(1) from trans_limit_white_list where merchant_no = #{merchantNo} and limit_action = #{limitAction} ")
    int selectTransLimitWhiteMerCount(@Param("merchantNo") String merchantNo,@Param("limitAction") String limitAction);

    @Select("select count(1) from trans_limit_white_list where merchant_no = #{merchantNo} and limit_action = #{limitAction} and  id != #{id}")
    int selectTransLimitWhiteMerCountById(@Param("merchantNo") String merchantNo,@Param("limitAction") String limitAction,@Param("id") Long id);

    @Insert("INSERT INTO trans_limit_white_list ( limit_action, merchant_no, remark, create_person) VALUES " +
            "(#{info.limitAction},#{info.merchantNo},#{info.remark},#{info.createPerson})")
    int insertTransLimitWhite(@Param("info") TransLimitWhite info);

    @Update("UPDATE trans_limit_white_list SET limit_action=#{info.limitAction}, remark=#{info.remark} WHERE id=#{info.id}")
    int updateTransLimitWhite(@Param("info") TransLimitWhite info);

    @Update("UPDATE trans_limit_white_list SET `status`=#{status} WHERE id=#{id}")
    int updateTransLimitWhiteStatus(@Param("status")Integer status,@Param("id")Long id);

    @Delete("delete from trans_limit_white_list where id=#{id}")
    int deleteTransLimitWhite(@Param("id")Long id);

    class SqlProvider{
        public String selectMinServiceManageQuota(final Map<String, Object> param) {
            final String teamId = (String) param.get("teamId");
            final String cardType = (String) param.get("cardType");
            return new SQL(){{
                SELECT("MIN(smq.single_day_amount) minSingleDayAmount,MIN(smq.single_count_amount) minSingleCountAmount," +
                        "MIN(smq.single_daycard_amount) minSingleDaycardAmount,MIN(smq.single_daycard_count) minSingleDaycardCount");
                FROM("business_product_define  bpd");
                INNER_JOIN("business_product_info bpi on bpd.bp_id = bpi.bp_id");
                INNER_JOIN("service_info si on si.service_id = bpi.service_id");
                INNER_JOIN("service_manage_quota smq on si.service_id = smq.service_id and smq.agent_no ='0'");
                if(!"all".equals(teamId)){
                    String teamIds[]=teamId.split(",");
                    String teamIdStr="";
                    for (int i=0;i<teamIds.length;i++){
                        teamIdStr+="'"+teamIds[i]+"',";
                    }
                    teamIdStr=teamIdStr.substring(0,teamIdStr.length()-1);
                    WHERE("bpd.team_id in ("+teamIdStr+")");
                }
                WHERE("smq.card_type = #{cardType}");
                WHERE("bpd.allow_individual_apply='1' and bpd.effective_status ='1' and si.service_type ='4'  and si.service_status='1'");
            }}.toString();
        }

        public String selectTransLimitRuleList(final Map<String, Object> param) {
            final TransLimitRule info = (TransLimitRule) param.get("info");
            SQL sql = new SQL(){{
                SELECT("tlr.*,(SELECT group_concat(ti.team_name) FROM team_info ti where  FIND_IN_SET (ti.team_id,tlr.team_id)) teamName");
                FROM("trans_limit_rule tlr");
                WHERE("tlr.`status`!=-1");
                if(StringUtil.isNotBlank(info.getTeamId())){
                    WHERE("tlr.team_id like concat('%',#{info.teamId},'%') ");
                }
                if(StringUtil.isNotBlank(info.getCardType())){
                    WHERE("tlr.card_type = #{info.cardType} ");
                }
                if(StringUtil.isNotBlank(info.getRulesProvinces())){
                    WHERE("tlr.rules_provinces like concat('%',#{info.rulesProvinces},'%')");
                }
                if(StringUtil.isNotBlank(info.getStatus())){
                    WHERE("tlr.`status` = #{info.status} ");
                }
                if(StringUtil.isNotBlank(info.getCreatePerson())){
                    WHERE("tlr.create_person like concat('%',#{info.createPerson},'%')");
                }
                if(StringUtil.isNotBlank(info.getLimitAction())){
                    WHERE("tlr.limit_action = #{info.limitAction} ");
                }
                if(StringUtil.isNotBlank(info.getCreateTimeBegin())){
                    WHERE("tlr.create_time >= #{info.createTimeBegin} ");
                }
                if(StringUtil.isNotBlank(info.getCreateTimeEnd())){
                    WHERE("tlr.create_time <= #{info.createTimeEnd} ");
                }
                ORDER_BY("tlr.create_time desc");
            }};
            return sql.toString();
        }

        public String selectTransLimitWhiteList(final Map<String, Object> param) {
            final TransLimitWhite info = (TransLimitWhite) param.get("info");
            SQL sql = new SQL(){{
                SELECT("tlwl.*,mi.mobilephone");
                FROM("trans_limit_white_list tlwl");
                LEFT_OUTER_JOIN("merchant_info mi on mi.merchant_no=tlwl.merchant_no");
                if(StringUtil.isNotBlank(info.getMobilephone())){
                    WHERE("mi.mobilephone = #{info.mobilephone} ");
                }
                if(StringUtil.isNotBlank(info.getMerchantNo())){
                    WHERE("tlwl.merchant_no = #{info.merchantNo} ");
                }
                if(StringUtil.isNotBlank(info.getStatus())){
                    WHERE("tlwl.`status` = #{info.status} ");
                }
                if(StringUtil.isNotBlank(info.getCreatePerson())){
                    WHERE("tlwl.create_person like concat('%',#{info.createPerson},'%')");
                }
                if(StringUtil.isNotBlank(info.getLimitAction())){
                    WHERE("tlwl.limit_action = #{info.limitAction} ");
                }
                if(StringUtil.isNotBlank(info.getCreateTimeBegin())){
                    WHERE("tlwl.create_time >= #{info.createTimeBegin} ");
                }
                if(StringUtil.isNotBlank(info.getCreateTimeEnd())){
                    WHERE("tlwl.create_time <= #{info.createTimeEnd} ");
                }
                ORDER_BY("tlwl.create_time desc");
            }};
            return sql.toString();
        }
    }
}
